// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:async';
import 'dart:io';

import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/module/world/audio/player/audio_download.dart';
import 'package:path_provider/path_provider.dart';

import '../../../../common/window_pop/public_btn_tem.dart';
import '../../../../common/window_pop/public_btn_widget.dart';
import '../../../world/world_audio_publish/waveforms_widget.dart';
import 'audio_card_record_logic.dart';
import 'audio_card_record_state.dart';
import 'audio_record_config.dart';

/// @description:
/// @author
/// @date: 2025-01-20 09:58:27
class AudioCardRecordRestultWidget extends StatefulWidget {
  const AudioCardRecordRestultWidget({
    Key? key,
    required this.playArea,
    required this.deleteAudioCallBack,
    required this.againAudioCallBack,
  }) : super(key: key);
  final PlayArea playArea;
  final Function deleteAudioCallBack;
  final Function againAudioCallBack;

  @override
  State<AudioCardRecordRestultWidget> createState() => _AudioCardRecordRestultWidgetState();
}

class _AudioCardRecordRestultWidgetState extends State<AudioCardRecordRestultWidget> {
  final AudioCardRecordLogic logic = Get.put(AudioCardRecordLogic());

  final AudioCardRecordState state = Get.find<AudioCardRecordLogic>().state;

  bool isLoading = false;
  String voiceFilePath = '';

  PublicBtnItem? voiceAgain;
  PublicBtnItem? voiceDelete;

  @override
  void initState() {
    super.initState();
    // PermissionUtils.microphone();

    String audioUrl = widget.playArea.voice?.src ?? '';
    AudioDownLoad.getFile(
        filePath: audioUrl,
        onProgress: (progress) {},
        onNetComplete: (url) {
          isLoading = true;
          setState(() {});
        },
        onError: () {
          isLoading = false;
          setState(() {});
        },
        complete: (filePath) {
          voiceFilePath = filePath;
          if (isLoading == true) {
            isLoading = false;
          }
          if (mounted) {
            setState(() {});
          }
          logs('voiceFilePath  = $voiceFilePath');
        });

    for (PublicBtnItem element in widget.playArea.btns ?? []) {
      if (element.key == 'voiceAgain') {
        voiceAgain = element;
      }
      if (element.key == 'voiceDelete') {
        voiceDelete = element;
      }
    }
  }

  Future<String> getAudiopath() async {
    Directory appDirectory = await getApplicationDocumentsDirectory();
    String audioPath = "${appDirectory.path}/recording.m4a";
    return audioPath;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20),
      child: Stack(
        children: [
          Image.asset('assets/app/images/world/audio_play_bg.png'),
          Positioned(
              top: 10,
              left: 0,
              right: 0,
              child: Center(
                child: voiceFilePath.isNotEmpty
                    ? WaveformsWidget(
                        width: 120,
                        waveformsHeight: 25,
                        bgColor: const Color(0xFF3C9CF1),
                        radius: 30,
                        audioPath: voiceFilePath)
                    : const SizedBox(),
              )),
          Positioned(
              bottom: 20,
              left: 0,
              right: 0,
              height: 40.h,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  if (voiceDelete != null)
                    PublicButtonWidget(
                      btnItem: voiceDelete!,
                      alertCallBack: (item) {
                        publicButtonAction(item: item);
                      },
                      clickAction: (btnItem) {},
                      child: Container(
                        width: 115.w,
                        height: 45.h,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: const Color(0xFFFFFFFF), borderRadius: BorderRadius.all(Radius.circular(22.5.r))),
                        child: Text(
                          voiceDelete?.title ?? "删除声音",
                          style:
                              TextStyle(color: const Color(0xFFF74437), fontWeight: FontWeight.w400, fontSize: 16.sp),
                        ),
                      ),
                    ),
                  if (voiceAgain != null)
                    PublicButtonWidget(
                      btnItem: voiceAgain!,
                      alertCallBack: (item) {
                        publicButtonAction(item: item);
                      },
                      clickAction: (btnItem) {},
                      child: Container(
                        width: 115.w,
                        height: 45.h,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: const Color(0xFF25D4D0), borderRadius: BorderRadius.all(Radius.circular(22.5.r))),
                        child: Text(
                          voiceAgain?.title ?? "重新录制",
                          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w400, fontSize: 16.sp),
                        ),
                      ),
                    )
                ],
              ))
        ],
      ),
    );
  }

  void publicButtonAction({required WindowBtn item}) {
    if (item.btnData?.click?.react == 'option' && item.btnData?.click?.option == 'delrecord') {
      // 删除声音文件
      widget.deleteAudioCallBack.call();
    }
    if (item.btnData?.click?.react == 'jump') {
      // 重新录制声音文件
      String query = item.btnData?.click?.params?.query ?? '';
      if (query.isNotEmpty) {
        widget.againAudioCallBack.call();
        // Get.to(const AudioCardRecordPage());
      }
    }
  }
}
